/* jshint esversion: 6 */
const Router = require('koa-router');
const tool = require("../../tools/tool");
const router = new Router();
const {db, Op, QueryTypes} = require("../../models/db");
// 修改密码
router.post('/user/scanLogined', async ctx => {
    let code = ctx.request.body.code
    let model = await db.models['loginScan'].findOne({
        where: {
            scanCode: code
        }
    })
    if (model) {
        if(model.confirm === 0) {
            model.confirm = 1
            await model.save()
            let user = await db.models['admin'].findOne({
                where: {
                    token: model.userToken
                }
            })
            if (user) {
                // return login(user.username, user.userpwd, ctx)
            }
            return ctx.suc('')
        }
        else {
            return ctx.err('二维码过期')
        }
        return ctx.err('')
    }
    return ctx.err('')
})

router.post('/user/setScanLogin', async ctx => {
    let code = ctx.request.body.code
    if(code) {
        let scan = await db.models['loginScan'].findOne({
            where: {
                scanCode: code
            }
        })
        if (!scan) {
            const mode = await db.models['loginScan'].create({
                scanCode: code,
                userToken: ctx.user.token,
                confirm: 0,
                ctime: tool.getTime()
            })
            return ctx.suc('', mode)
        }
        else {
            scan.userToken = ctx.user.token
            await scan.save()
            return ctx.suc('', scan)
        }
    }
    else {
        return ctx.err('扫码登录失败')
    }
})
router.post('/user/setTers', async ctx => {
    let areaId = ctx.request.body.id;
    let model = await db.models['area'].findOne({
        where: {
            id: areaId
        }
    })
    if(model) {
        let c = await db.models['contact'].count({
            where: {
                areaId: areaId
            }
        })
        model.ters = c
        await model.save()
    }
    ctx.suc('')
})




module.exports = router;